(function() {
	$.namespace("com.yogi.wrappers.member");

	/**
	 * { "type":"member_logon",
	 * "register_catalog":"catalog_for_member_to_input_form",
	 * "mod_info_catalog":"catalog_for_member_to_modify_information",
	 * "findpwd_catalog":"catalog_for_member_to_fetch_pwd" }
	 */
	com.yogi.wrappers.member.MemberLogonWrapper = function() {
		com.yogi.wrappers.member.MemberLogonWrapper.superclass.constructor
				.call(this);
		com.yogi.wrappers.member.MemberLogonWrapper.EVENT_LOGIN_SUCCESS = "EVENT_LOGIN_SUCCESS";
		com.yogi.wrappers.member.MemberLogonWrapper.EVENT_LOGOUT_SUCCESS = "EVENT_LOGOUT_SUCCESS";
		com.yogi.wrappers.member.MemberLogonWrapper.login_member_info = false;
	};
	Ext
			.extend(
					com.yogi.wrappers.member.MemberLogonWrapper,
					com.yogi.core.PartWrapperBase,
					{
						wrap : function(part, wrapperConfig, partConfig) {
							com.yogi.wrappers.member.MemberLogonWrapper.superclass
									.wrap(part, wrapperConfig, partConfig);

							var context = this;
							var logon_delegate = false;
							var welcome_delegate = false;

							var member_login_done = false;
							var div_before = false;
							var div_after = false;

							function setupElements() {
								div_before = part.getElement("div_before");
								div_after = part.getElement("div_after");
							}
							function showPanel() {
								if (member_login_done) {
									div_before.hide();
									if (div_after) {
										div_after.show();
										//console	.log(com.yogi.wrappers.member.MemberLogonWrapper.login_member_info);
										welcome_delegate
												.showUserName(com.yogi.wrappers.member.MemberLogonWrapper.login_member_info.UserName);
									}
								} else {
									div_before.show();
									if (div_after) {
										div_after.hide();
									}
								}
							}
							function initLogonPanel() {
								logon_delegate = new com.yogi.wrappers.member.LoginForm(
										div_before, part, wrapperConfig);
								$(logon_delegate)
										.bind(
												com.yogi.wrappers.member.MemberLogonWrapper.EVENT_LOGIN_SUCCESS,
												onLoginSuccess);
							}
							function onLoginSuccess(evt, data) {
//								console.log("onLoginSuccess:");
//								console.log(data);
								member_login_done = true;
								com.yogi.wrappers.member.MemberLogonWrapper.login_member_info = data;
								showPanel();
							}
							function onLogoutSuccess(evt, data) {
								member_login_done = false;
								showPanel();
							}
							function initWelcomePanel() {
								welcome_delegate = new com.yogi.wrappers.member.LoginDoneForm(
										div_after, part, wrapperConfig);
								$(welcome_delegate)
										.bind(
												com.yogi.wrappers.member.MemberLogonWrapper.EVENT_LOGOUT_SUCCESS,
												onLogoutSuccess);
							}
							part.waitForDiv(function(partComp) {
								setupElements();
								initLogonPanel();
								initWelcomePanel();
								showPanel();
							});
						}
					});
	com.yogi.wrappers.member.LoginForm = function(ct, part, wrapperConfig) {
		var context = this;
		var input_username = part.getElement("username");
		var input_password = part.getElement("password");
		var progressBar = part.getElement("process_bar");
		input_username.attr("maxlength", 20);
		input_password.attr("maxlength", 20);

		var btn_reg = part.getElement("btn_reg");
		btn_reg.attr("href", "javascript:void(0)");
		btn_reg.click(function() {
			window.contentPanel.loadCatalog(wrapperConfig.register_catalog);
		});

		var btn_findpwd = part.getElement("btn_findpwd");
		btn_findpwd.attr("href", "javascript:void(0)");
		btn_findpwd.click(function() {
			window.contentPanel.loadCatalog(wrapperConfig.findpwd_catalog);
		});

		var btn_login = part.getElement("btn_login");
		btn_login.attr("href", "javascript:void(0)");

		var form = ct.find("form")[0];
		var validator = $(form).validate({
			rules : {
				"username" : "required",
				"password" : "required"
			},
			messages : {
				"username" : "请输入用户名",
				"password" : "请输入密码"
			},
			onfocusout : false,
			onkeyup: false,
			showErrors : function(errorMap, errorList) {
				// console.log(errorMap);
				// console.log(errorList);
				var msg = "";
				Ext.each(errorList, function(err) {
					msg += err.message + "\n";
				});
				if (!Ext.isEmpty(msg)) {
					alert(msg);
					$(errorList[0].element).focus();
				}
			}
		});
		function showProgressBar(show) {
			if (show) {
				progressBar.show();
			} else {
				progressBar.hide();
			}
		}
		function loginMemberCallback(result) {
			// console.log("loginMemberCallback:");
			// console.log(result);
			if (result.success && result.data.Success) {
				input_password.val("");
				$(context)
						.trigger(
								com.yogi.wrappers.member.MemberLogonWrapper.EVENT_LOGIN_SUCCESS,
								result.data.Context);
			} else {
				alert(result.data.Describe);
			}
			showProgressBar(false);
		}
		btn_login.click(function() {
			if (validator.form()) {
				var form_data = $(form).serializeObject();
				var virDir = window.contentPanel.getVirDir();
				if (virDir[virDir.length - 1] != '/')
					virDir += '/';
				var rm = new com.yogi.core.net.RemoteMethod(virDir
						+ "Web/ashx/Handler_MemberLogin.ashx");
				var params = [ {
					"YCBPI" : "YogiCRM",
					Client : "flash"
				}, {
					"UserName" : form_data["username"],
					"Password" : form_data["password"]
				} ];
				showProgressBar(true);
				rm.callMethod("LoginMember", params, loginMemberCallback);
			}
		});
	};
	com.yogi.wrappers.member.LoginDoneForm = function(ct, part, wrapperConfig) {
		var context = this;
		var txt_username = part.getElement("txt_username");
		var btn_quit = part.getElement("btn_quit");
		var btn_modify = part.getElement("btn_modify");
		var progressBar = part.getElement("process_bar2");

		function showProgressBar(show) {
			if (show) {
				progressBar.show();
			} else {
				progressBar.hide();
			}
		}
		function logoutMemberCallback(result) {
			if (result.success && result.data.Success) {
				com.yogi.wrappers.member.MemberLogonWrapper.login_member_info = null;
				$(context)
						.trigger(
								com.yogi.wrappers.member.MemberLogonWrapper.EVENT_LOGOUT_SUCCESS);
			} else {
				alert(result.data.Describe);
			}
			showProgressBar(false);
		}
		btn_quit.attr("href", "javascript:void(0)");
		btn_quit.click(function() {
			var virDir = window.contentPanel.getVirDir();
			if (virDir[virDir.length - 1] != '/')
				virDir += '/';
			var rm = new com.yogi.core.net.RemoteMethod(virDir
					+ "Web/ashx/Handler_MemberLogin.ashx");
			showProgressBar(true);
			rm.callMethod("LogoutMember", [ {
				"YCBPI" : "YogiCRM",
				Client : "flash"
			} ], logoutMemberCallback, null);
		});

		btn_modify.attr("href", "javascript:void(0)");
		btn_modify.click(function() {
			window.contentPanel.loadCatalog(wrapperConfig.mod_info_catalog);
		});
		this.showUserName = function(uname) {
			console.log(uname);
			txt_username.val(uname);
			txt_username.attr("readonly", true);
		};
	};

	/**
	 * { "type":"member_fetchpwd", "catalog":"catalog of member fetch password" }
	 */
	com.yogi.wrappers.member.MemberFetchPwdWrapper = function() {
		com.yogi.wrappers.member.MemberFetchPwdWrapper.superclass.constructor
				.call(this);
	};
	Ext.extend(com.yogi.wrappers.member.MemberFetchPwdWrapper,
			com.yogi.core.PartWrapperBase, {
				wrap : function(part, wrapperConfig, partConfig) {
					com.yogi.wrappers.member.MemberFetchPwdWrapper.superclass
							.wrap(part, wrapperConfig, partConfig);

					var formpanel = false;
					part.waitForDiv(function(partComp) {
						formpanel = new com.yogi.wrappers.member.FetchPwdForm(
								part, wrapperConfig);
					});
				}
			});
	com.yogi.wrappers.member.FetchPwdForm = function(part, wrapperConfig) {
		var txt_username = part.getElement("txt_username");
		var txt_email = part.getElement("txt_email");
		var btn_ok = part.getElement("btn_ok");
		btn_ok.attr("href", "javascript:void(0)");
		var btn_cancel = part.getElement("btn_cancel");
		btn_cancel.attr("href", "javascript:void(0)");
		var progressBar = part.getElement("process_bar");

		function showProgressBar(show) {
			if (show) {
				progressBar.show();
			} else {
				progressBar.hide();
			}
		}
		function onCatalogChange(event, data) {
			if (data.current == wrapperConfig.catalog) {
				txt_username.focus();
			}
		}
		$(window.contentPanel)
				.bind(com.yogi.core.ContentPanel.CATALOGLOADED_EVENT,
						onCatalogChange);

		var form = part.getDIV().find("form")[0];
		var validator = $(form).validate({
			rules : {
				"txt_username" : "required",
				"txt_email" : {
					required: true,
				    email: true
				}
			},
			messages : {
				"txt_username" : "请输入用户名",
				"txt_email" :  {
					required: "请输入Email地址",
					email: "请输入正确的email地址"
			    }
			},
			onfocusout : false,
			onkeyup: false,
			showErrors : function(errorMap, errorList) {
				var msg = "";
				Ext.each(errorList, function(err) {
					msg += err.message + "\n";
				});
				if (!Ext.isEmpty(msg)) {
					alert(msg);
					$(errorList[0].element).focus();
				}
			}
		});
		btn_ok.click(function() {
			if (validator.form()) {
				var form_data = $(form).serializeObject();
				var virDir = window.contentPanel.getVirDir();
				if (virDir[virDir.length - 1] != '/')
					virDir += '/';
				var rm = new com.yogi.core.net.RemoteMethod(virDir
						+ "Web/ashx/Handler_MemberLogin.ashx");
				var params = [ {
					"YCBPI" : "YogiCRM",
					Client : "flash"
				}, form_data["txt_username"], form_data["txt_email"] ];
				showProgressBar(true);
				rm.callMethod("fetchPwd", params, function(result) {
					if (result.success && result.data.Success) {
						alert("密码已经发送到您的邮箱");
					} else {
						alert("密码发送失败:" + result.data.Describe);
					}
					showProgressBar(false);
				});
			}
		});
		btn_cancel.click(function() {
			window.contentPanel.loadHomePage();
		});
	};
	/**
	 * { "type":"member_register", "catalog":"catalog of member_register" }
	 */
	com.yogi.wrappers.member.MemberRegisterWrapper = function() {
		com.yogi.wrappers.member.MemberRegisterWrapper.superclass.constructor
				.call(this);
	};
	Ext.extend(com.yogi.wrappers.member.MemberRegisterWrapper,com.yogi.core.PartWrapperBase, {
		wrap : function(part, wrapperConfig, partConfig) {
			com.yogi.wrappers.member.MemberRegisterWrapper.superclass.wrap(part, wrapperConfig, partConfig);
			part.waitForDiv(function(partComp) {
					new com.yogi.wrappers.member.RegisterForm(part, wrapperConfig);
			} );			
		}
	});
	com.yogi.wrappers.member.GetMemberFormValidateRule = function(form,part) {
		var validator = $(form).validate({
			rules : {
				"UserName" : "required",
				"Email" : {
					required: true,
				    email: true
				},
				"Password":  {
					required: true,
					minlength: 6
				},
				"CheckPassword": {
					required: true,
					minlength: 6,
				    equalTo: "#" + part.getElementId("Password")
				},
				"Phone": "required"
			},
			messages : {
				"UserName" : "请输入用户名",
				"Email" :  {
					required: "请输入Email地址",
					email: "请输入正确的email地址"
			    },
				"Password" : {
				    required: "请输入密码",
				    minlength: "密码不能小于6个字符"
				},
				"CheckPassword" : {
				    required: "请输入确认密码",
				    minlength: "确认密码不能小于6个字符",
				    equalTo: "两次输入密码不一致"
			    },
				"Phone" : "请输入电话号码"
			},
			onfocusout : false,
			onkeyup: false,
			showErrors : function(errorMap, errorList) {
				var msg = "";
				Ext.each(errorList, function(err) {
					msg += err.message + "\n";
				});
				if (!Ext.isEmpty(msg)) {
					alert(msg);
					$(errorList[0].element).focus();
				}
			}
		});
		return validator;
	};
	com.yogi.wrappers.member.RegisterForm = function( part, wrapperConfig) {		
		var m_pageStack = new com.yogi.runtime.PageStack();
		var div_reg_form = part.getElement("reg_form");
		div_reg_form.css("position","relative");
		m_pageStack.addPage(div_reg_form);
		var div_prompt_msg = part.getElement("prompt_msg");
		var div_prompt_div = part.getElement("div_prompt");
		var btn_prompt_ok = part.getElement("btn_prompt_ok");
		div_prompt_msg.css("position","relative");
		div_prompt_msg.css("left", (div_reg_form.width() - div_prompt_msg.width()) / 2);
		m_pageStack.addPage(div_prompt_msg);
		var div_progress_msg = part.getElement("progress_msg");
		div_progress_msg.css("position","relative");
		div_progress_msg.css("left", (div_reg_form.width() - div_progress_msg.width()) / 2);
		m_pageStack.addPage(div_progress_msg);
		var div_success_msg = part.getElement("success_msg");
		div_success_msg.css("position","relative");
		div_success_msg.css("left", (div_reg_form.width() - div_success_msg.width()) / 2);
		m_pageStack.addPage(div_success_msg);
		
		
		var btn_submit = part.getElement("btn_submit");
		btn_submit.attr("href", "javascript:void(0)");
		var btn_reset = part.getElement("btn_reset");
		btn_reset.attr("href", "javascript:void(0)");
		
		var form = part.getDIV().find("form")[0];
		var validator = com.yogi.wrappers.member.GetMemberFormValidateRule( form, part );
		function showPrompt(msg) {
			m_pageStack.showPage(div_prompt_msg);
			div_prompt_div.html(msg);
		}
		btn_submit.click(function(){
			if (validator.form()) {
				var form_data = $(form).serializeObject();
				var virDir = window.contentPanel.getVirDir();
				if (virDir[virDir.length - 1] != '/')
					virDir += '/';
				var rm = new com.yogi.core.net.RemoteMethod(virDir
						+ "Web/ashx/Handler_MemberRegister.ashx");
				var params = [ {
					"YCBPI" : "YogiCRM",
					Client : "flash"
				}, form_data ];
				m_pageStack.showPage(div_progress_msg);
				rm.callMethod("RegisterMember", params, function(result) {
					if (result.success && result.data.Success) {
						 m_pageStack.showPage(div_success_msg);
						 form.reset();
						 (function(){
							 m_pageStack.showPage(div_reg_form);
						 }).defer(8000);
					} else {
						showPrompt("注册不成功.<p>" + result.data.Describe);
					}
				});
			}
		});
		btn_prompt_ok.click( function() {
			m_pageStack.showPage(div_reg_form);
		});
		btn_reset.click( function() {
			form.reset();
		});
	};
	/**
	 * { "type":"member_reg_info_mod"  }
	 */
	com.yogi.wrappers.member.MemberModificationWrapper = function() {
		com.yogi.wrappers.member.MemberModificationWrapper.superclass.constructor
				.call(this);
	};
	Ext.extend(com.yogi.wrappers.member.MemberModificationWrapper,com.yogi.core.PartWrapperBase, {
		wrap : function(part, wrapperConfig, partConfig) {
			com.yogi.wrappers.member.MemberModificationWrapper.superclass.wrap(part, wrapperConfig, partConfig);			
			part.waitForDiv(function(partComp) {
					new com.yogi.wrappers.member.ModificationForm(part, wrapperConfig);
			});
		}
	});
	com.yogi.wrappers.member.ModificationForm = function(part, wrapperConfig) {	
		var btn_submit = part.getElement("btn_submit");
		btn_submit.attr("href", "javascript:void(0)");
		var progressBar = part.getElement("process_bar");
		
		var form = part.getDIV().find("form")[0];
		var validator = com.yogi.wrappers.member.GetMemberFormValidateRule( form, part );
		
		setForm(com.yogi.wrappers.member.MemberLogonWrapper.login_member_info);
		
		function showProgressBar(show) {
			if (show) {
				progressBar.show();
			} else {
				progressBar.hide();
			}
		}
		function setForm(data) {
			   for(var fld in data) {
				   var val = data[fld];
				   if(fld == "Password") {
					   continue;
				   }
				   if(["MemberGender","MemberGender","Education"].indexOf(fld) >= 0) {
					   $(form).find("input:[name=" + fld + "]:radio").each(function(){
						   if (this.value == val){
							   this.checked=true;
						   }
					   });
				   } else {
				   		$(form[fld]).val(val);
				   }
			   }
			   $(form).find("input:[name=UserName]").attr("readonly",true);
		}
		btn_submit.click( function() {
			if (validator.form()) {
				var form_data = $(form).serializeObject();
				form_data["Id"] = com.yogi.wrappers.member.MemberLogonWrapper.login_member_info.Id;
				var virDir = window.contentPanel.getVirDir();
				if (virDir[virDir.length - 1] != '/')  virDir += '/';
				var rm = new com.yogi.core.net.RemoteMethod(virDir	+ "Web/ashx/Handler_MemberRegister.ashx");
				var params = [ {
					"YCBPI" : "YogiCRM",
					Client : "flash"
				}, form_data ];
				
				showProgressBar(true);
				rm.callMethod("ModifyMember", params, function(result)  {
					if (result.success && result.data.Success)  {
						 alert("资料修改成功");
					} else {
						 alert("资料修改不成功.<p>" + result.data.Describe);
					}
					showProgressBar(false);
				});
			}
		});		
	};		
	var wrapperManager = window.contentPanel.getWrapperManager();
	wrapperManager.registerWrapperClass("member_logon",	com.yogi.wrappers.member.MemberLogonWrapper);
	wrapperManager.registerWrapperClass("member_fetchpwd", com.yogi.wrappers.member.MemberFetchPwdWrapper);
	wrapperManager.registerWrapperClass("member_register", com.yogi.wrappers.member.MemberRegisterWrapper);
	wrapperManager.registerWrapperClass("member_reg_info_mod", com.yogi.wrappers.member.MemberModificationWrapper);

})();